package com.hxci.liminshuo.controller;

import com.hxci.liminshuo.pojo.MinShuoCourse;
import com.hxci.liminshuo.servcie.MinShuoCorseService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@CrossOrigin(origins = "*")
@RestController
@Controller
@RequestMapping("support")
public class MinShuoCustomerSupportController {

    @Autowired
    private MinShuoCorseService courseService;

    // 直接返回HTML页面
    @GetMapping(value = "chat", produces = "text/html;charset=UTF-8")
    public String chatView() {
        return """
            <!DOCTYPE html>
            <html lang="zh-CN">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>智能客服</title>
                <style>
                    .chat-container {
                        width: 600px;
                        margin: 20px auto;
                        border: 1px solid #5c2d91;
                        border-radius: 8px;
                        overflow: hidden;
                        background-color: #2d1b55;
                        color: #ffffff;
                    }
                    .chat-header {
                        background-color: #7b2cbf;
                        padding: 15px;
                        font-size: 18px;
                        font-weight: bold;
                        text-align: center;
                    }
                    .chat-content {
                        height: 400px;
                        overflow-y: auto;
                        padding: 15px;
                    }
                    .message {
                        margin: 10px 0;
                        padding: 10px;
                        border-radius: 6px;
                        max-width: 70%;
                        word-wrap: break-word;
                    }
                    .user-message {
                        background-color: #7b2cbf;
                        margin-left: auto;
                        text-align: right;
                    }
                    .system-message {
                        background-color: #4a256d;
                        margin-right: auto;
                    }
                    .message-time {
                        font-size: 12px;
                        color: #b39ddb;
                        text-align: right;
                        margin-top: 5px;
                    }
                    .input-area {
                        display: flex;
                        padding: 10px;
                        border-top: 1px solid #5c2d91;
                    }
                    .input-area input {
                        flex: 1;
                        padding: 10px;
                        border: 1px solid #5c2d91;
                        border-radius: 4px;
                        background-color: #3d2269;
                        color: #ffffff;
                        outline: none;
                    }
                    .input-area button {
                        margin-left: 10px;
                        padding: 0 20px;
                        background-color: #7b2cbf;
                        color: white;
                        border: none;
                        border-radius: 4px;
                        cursor: pointer;
                    }
                    .input-area button:hover {
                        background-color: #9c27b0;
                    }
                </style>
            </head>
            <body>
            <div class="chat-container">
                <div class="chat-header">智能客服</div>
                <div class="chat-content" id="chatContent">
                    <div class="message system-message">
                        您好！我是智能客服助手<br>
                        输入"统计"可查看实时课程统计信息
                    </div>
                </div>
                <div class="input-area">
                    <input type="text" id="messageInput" placeholder="请输入指令..." onkeydown="if(event.key === 'Enter') sendMessage()">
                    <button onclick="sendMessage()">发送</button>
                </div>
            </div>

            <script>
                function sendMessage() {
                    const input = document.getElementById("messageInput");
                    const msg = input.value.trim();
                    if (!msg) return;

                    const chatContent = document.getElementById("chatContent");
                    const time = new Date().toLocaleTimeString();

                    // 添加用户消息
                    const userMessageDiv = document.createElement('div');
                    userMessageDiv.className = 'message user-message';
                    userMessageDiv.innerHTML = `${msg}<div class="message-time">${time}</div>`;
                    chatContent.appendChild(userMessageDiv);
                    
                    input.value = "";
                    scrollToBottom(chatContent);

                    // 显示加载状态
                    const loadingDiv = document.createElement('div');
                    loadingDiv.className = 'message system-message';
                    loadingDiv.innerHTML = '正在查询中...<div class="message-time">' + time + '</div>';
                    chatContent.appendChild(loadingDiv);
                    scrollToBottom(chatContent);

                    // 调用后端接口获取实时数据
                    fetch('/support/message?message=' + encodeURIComponent(msg))
                        .then(res => {
                            if (!res.ok) throw new Error(`后端接口异常（状态码：${res.status}）`);
                            return res.json();
                        })
                        .then(data => {
                            console.log("后端返回数据:", data);
                            
                            // 移除加载消息
                            chatContent.removeChild(loadingDiv);
                            
                            if (data.action && data.action.type === "statistics") {
                                const statsData = data.action.data;
                                if (statsData) {
                                    const totalCourses = statsData.totalCourses || 0;
                                    const coursesByTeacher = statsData.coursesByTeacher || {};
                                    
                                    let statsText = "课程统计信息如下<br>";
                                    statsText += `总课程数：${totalCourses} 门<br>`;
                                    statsText += "各教师课程数量：<br>";
                                    
                                    const teacherEntries = Object.entries(coursesByTeacher);
                                    if (teacherEntries.length === 0) {
                                        statsText += "• 暂无教师数据";
                                    } else {
                                        teacherEntries.forEach(([name, count], index) => {
                                            const lineBreak = index === teacherEntries.length - 1 ? "" : "<br>";
                                            statsText += `• ${name}：${count} 门${lineBreak}`;
                                        });
                                    }
                                    
                                    const statsDiv = document.createElement('div');
                                    statsDiv.className = 'message system-message';
                                    statsDiv.innerHTML = statsText + '<div class="message-time">' + new Date().toLocaleTimeString() + '</div>';
                                    chatContent.appendChild(statsDiv);
                                }
                            } else {
                                const reply = data.answer || "请输入'统计'查看课程信息";
                                const replyDiv = document.createElement('div');
                                replyDiv.className = 'message system-message';
                                replyDiv.innerHTML = reply + '<div class="message-time">' + new Date().toLocaleTimeString() + '</div>';
                                chatContent.appendChild(replyDiv);
                            }
                            scrollToBottom(chatContent);
                        })
                        .catch(error => {
                            console.error("请求错误:", error);
                            chatContent.removeChild(loadingDiv);
                            const errorDiv = document.createElement('div');
                            errorDiv.className = 'message system-message';
                            errorDiv.innerHTML = '请求失败：' + error.message + '<div class="message-time">' + new Date().toLocaleTimeString() + '</div>';
                            chatContent.appendChild(errorDiv);
                            scrollToBottom(chatContent);
                        });
                }

                function scrollToBottom(el) {
                    el.scrollTop = el.scrollHeight;
                }
            </script>
            </body>
            </html>
            """;
    }


    @ResponseBody
    @RequestMapping("message")
    public Map<String, Object> handleMessage(
            @RequestParam("message") String message,
            HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        Map<String, Object> actionResult = checkAndExecuteAction(message.trim(), request);

        if (actionResult != null) {
            response.put("action", actionResult);
            response.put("answer", actionResult.get("message"));
        } else {
            response.put("answer", "支持操作：统计、添加课程、修改课程、删除课程");
        }
        return response;
    }

    private Map<String, Object> checkAndExecuteAction(String message, HttpServletRequest request) {
        Map<String, Object> res = new HashMap<>();

        /* 1. 统计功能 */
        if (message.contains("统计") || message.contains("查看统计") || message.contains("显示统计") || message.contains("课程统计")) {
            List<MinShuoCourse> allCourses = courseService.query();   // ① 查库
            int total = (allCourses == null ? 0 : allCourses.size());

            /* ② 用 LinkedHashMap 保证教师顺序 */
            Map<String, Long> teacherStats = new LinkedHashMap<>();
            if (allCourses != null) {
                for (MinShuoCourse c : allCourses) {
                    String t = (c.getTea() == null || c.getTea().isBlank()) ? "未知教师" : c.getTea();
                    teacherStats.merge(t, 1L, Long::sum);
                }
            }

            /* ③ 一次性把两个字段放进同一个 Map，避免匿名 HashMap 打乱顺序 */
            Map<String, Object> data = new LinkedHashMap<>();
            data.put("totalCourses", total);
            data.put("coursesByTeacher", teacherStats);

            res.put("type", "statistics");
            res.put("data", data);
            res.put("message", "课程统计信息如下");
            return res;
        }
        /* 以下功能代码与顺序无关，保持原样即可 */
        // 2. 添加课程功能
        if (message.matches(".*添加课程.*")) {
            MinShuoCourse course = extractCourseFromMessage(message);

            if (course.getCname() == null || course.getCname().trim().isEmpty()) {
                res.put("type", "add_failed");
                res.put("message", "添加失败：请提供课程名称（例：添加课程 名称:数学）");
                return res;
            }

            if (course.getTea() == null || course.getTea().trim().isEmpty()) {
                res.put("type", "add_warn");
                res.put("message", "提示：未输入教师信息，将默认设为'未知教师'，是否继续？（发送：添加课程 名称:" + course.getCname() + ",教师:未知教师）");
                return res;
            }

            try {
                int rows = courseService.insert(course);
                if (rows > 0) {
                    res.put("type", "add_success");
                    res.put("message", "添加成功！课程：" + course.getCname() + "，教师：" + course.getTea());
                } else {
                    res.put("type", "add_failed");
                    res.put("message", "添加失败：数据库操作未生效");
                }
            } catch (Exception e) {
                res.put("type", "add_failed");
                res.put("message", "添加失败：" + e.getMessage().substring(0, 50));
            }
            return res;
        }

        // 3. 修改课程功能
        if (message.matches(".*(修改|更新|编辑).*课程.*")) {
            Integer courseId = extractCourseId(message);
            if (courseId == null) {
                res.put("type", "update_failed");
                res.put("message", "未识别课程ID（例：修改课程 1 名称:新名称）");
                return res;
            }

            MinShuoCourse existingCourse = courseService.selectById(courseId);
            if (existingCourse == null) {
                res.put("type", "update_failed");
                res.put("message", "课程ID不存在：" + courseId);
                return res;
            }

            MinShuoCourse updateData = extractCourseFromMessage(message);
            boolean hasUpdate = false;

            if (updateData.getCname() != null && !updateData.getCname().isEmpty()) {
                existingCourse.setCname(updateData.getCname());
                hasUpdate = true;
            }
            if (updateData.getTea() != null && !updateData.getTea().isEmpty()) {
                existingCourse.setTea(updateData.getTea());
                hasUpdate = true;
            }
            if (updateData.getMark() != null && !updateData.getMark().isEmpty()) {
                existingCourse.setMark(updateData.getMark());
                hasUpdate = true;
            }
            if (!hasUpdate) {
                res.put("type", "update_failed");
                res.put("message", "未识别修改内容（例：修改课程 1 教师:新老师）");
                return res;
            }

            int rows = courseService.update(existingCourse);
            if (rows > 0) {
                res.put("type", "update_success");
                res.put("message", "修改成功！课程ID：" + courseId);
            } else {
                res.put("type", "update_failed");
                res.put("message", "修改失败，请重试");
            }
            return res;
        }

        // 4. 删除课程功能
        if (message.matches(".*(删除|移除).*课程.*")) {
            Integer courseId = extractCourseId(message);
            if (courseId == null) {
                res.put("type", "delete_failed");
                res.put("message", "未识别课程ID（例：删除课程 1）");
                return res;
            }

            int rows = courseService.deleteById(courseId);
            if (rows > 0) {
                res.put("type", "delete_success");
                res.put("message", "删除成功！课程ID：" + courseId);
            } else {
                res.put("type", "delete_failed");
                res.put("message", "删除失败：课程ID不存在或已删除");
            }
            return res;
        }

        return null;
    }

    /* 以下辅助方法保持原样 */
    private Integer extractCourseId(String message) {
        Matcher matcher = Pattern.compile("(课程|ID|编号)[:：\\s]*?(\\d+)").matcher(message);
        if (matcher.find()) {
            try {
                return Integer.parseInt(matcher.group(2).trim());
            } catch (NumberFormatException e) {
                return null;
            }
        }
        matcher = Pattern.compile("(\\d+)[:：\\s]*(课程|ID|编号)").matcher(message);
        if (matcher.find()) {
            try {
                return Integer.parseInt(matcher.group(1).trim());
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    private MinShuoCourse extractCourseFromMessage(String msg) {
        MinShuoCourse course = new MinShuoCourse();

        // 调试输出
        System.out.println("解析消息: " + msg);

        // 使用更精确的解析方法
        // 格式：名称:值 教师:值 简介:值
        String[] parts = msg.split("\\s+");

        for (String part : parts) {
            if (part.startsWith("名称:")) {
                String name = part.substring(3).trim();
                // 移除可能的分隔符
                name = name.replaceAll("[,，;；].*$", "");
                course.setCname(name);
                System.out.println("解析到名称: " + name);
            } else if (part.startsWith("教师:")) {
                String teacher = part.substring(3).trim();
                teacher = teacher.replaceAll("[,，;；].*$", "");
                course.setTea(teacher);
                System.out.println("解析到教师: " + teacher);
            } else if (part.startsWith("简介:")) {
                String description = part.substring(3).trim();
                description = description.replaceAll("[,，;；].*$", "");
                course.setMark(description);
                System.out.println("解析到简介: " + description);
            }
        }

        return course;
    }

    private String extractField(String msg, String prefixRegex, String endRegex) {
        String part = msg.replaceAll(".*?" + prefixRegex, "");
        part = part.replaceAll(endRegex + ".*", "");
        return part.trim().isEmpty() ? null : part.trim();
    }

}